/*
 *@Type ServerController.java
 * @Desc
 * @Author urmsone urmsone@163.com
 * @date 2024/6/13 12:20
 * @version
 */
package controller;

import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import service.*;
import utils.LoggerUtil;
import utils.Role;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Setter
@Getter
public class SocketServerController implements Controller {

    private final Logger LOGGER = LoggerFactory.getLogger(SocketServerController.class);
    private final String logFormat = "[SocketServerController][{}]: {}";
    private String host;
    private int port;
    private Store store;

    // 添加集群相关字段
    private ClusterSyncService clusterSyncService;
    private NodeService nodeService;
    private Node selfNode;

    //使用线程池
    private ExecutorService threadPool = Executors.newFixedThreadPool(10);

    public SocketServerController(String host, int port, Store store, Node selfNode, List<Node> clusterNodes) {
        this.host = host;
        this.port = port;
        this.store = store;

        // 初始化集群服务
        this.clusterSyncService = new ClusterSyncService(store, selfNode, clusterNodes);
        this.selfNode = selfNode;
        ((NormalStore) store).setClusterSyncService(clusterSyncService);
        this.nodeService = new NodeService(this.selfNode, clusterNodes);
        this.nodeService.setClusterSyncService(clusterSyncService);
    }

    @Override
    public void set(String key, String value) {

    }

    @Override
    public String get(String key) {
        return null;
    }

    @Override
    public void rm(String key) {

    }

    @Override
    public void startServer() {

        nodeService.start();

        // 只有主节点启动服务端口
        if (selfNode.getRole() == Role.MASTER) {
            try (ServerSocket serverSocket = new ServerSocket(port)) {

                LoggerUtil.info(LOGGER, logFormat,"startServer","Server started, waiting for connections...");

                while (true) {
                    try {
                        Socket socket = serverSocket.accept();
                        LoggerUtil.info(LOGGER, logFormat,"startServer","New client connected");
                        // 为每个客户端连接创建一个新的线程
                        // 接受连接后
                        threadPool.execute(new SocketServerHandler(socket, store));

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }



            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            LoggerUtil.info(LOGGER, logFormat, "startServer",
                    "Slave node started (no service port)");
        }

    }
}
